package com.yw.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class Tool01 {
    private static SqlSessionFactory sqlSessionFactory;
    private final static ThreadLocal<SqlSession> threadlocal=new ThreadLocal<>();

    static{
        try {
            InputStream resources= Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(resources);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        //通过线程获取连接？？？？
        SqlSession sqlSession=threadlocal.get();
        if (sqlSession==null){
            sqlSession=sqlSessionFactory.openSession();
            threadlocal.set(sqlSession);
        }
        return sqlSession;
    }
    public static void close(){
        SqlSession sqlSession=getSqlSession();
        sqlSession.close();
        threadlocal.remove();
    }
    public static void commit(){
        SqlSession sqlSession=getSqlSession();
        sqlSession.commit();
        close();
    }
    public static void roolback(){
        SqlSession sqlSession=getSqlSession();
        sqlSession.rollback();
        close();
    }
    //接口回调？？？？？？
    public static<T> T getMapper(Class<T> tClass){
        SqlSession sqlSession=getSqlSession();
        return sqlSession.getMapper(tClass);

    }

}
